package com.renne.core.config;

import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import org.noear.solon.annotation.*;

import javax.sql.DataSource;

/**
 * @author noear 2022/10/7 created
 */
@Slf4j
@Configuration
public class DataSourceConfigure {

    @Inject
    UpgradeConfigure upgradeConfigure;

    @Bean(name = "snowy", typed = true)
    public DataSource db1(@Inject("${snowy.datasource.dynamic.master}") HikariDataSource ds) {
        // 是否打印sql
        boolean logEnabled = Boolean.parseBoolean(Solon.cfg().get("mybatis.snowy.globalConfig.logEnabled", String.valueOf(false)));
        if (logEnabled) {
            AuditManager.setAuditEnable(true);
            ConsoleMessageCollector consoleMessageCollector = new ConsoleMessageCollector();
            AuditManager.setMessageCollector(consoleMessageCollector);
        }
        // 如果数据库连接是sqlite本地数据库，执行初始化SQLite数据库到本地目录操作
        if (ds.getDriverClassName().contains("sqlite")) {
            String url = ds.getJdbcUrl();
            ds.setJdbcUrl(url + UpgradeConfigure.getLocalDbPath());

            upgradeConfigure.initDatabase();
        }
        log.info("使用本地数据库，url:{}", ds.getJdbcUrl());
        return ds;
    }

//    @Bean
//    public void db1Init(@Db("db1")MybatisConfiguration configuration){
//        //这块，赞时不支持配置。手动处理下
//        configuration.getTypeHandlerRegistry().register("vip.xiaonuo.common.handler");
//    }
}
